<template>
    <el-dialog v-if="dialogVisible" :close-on-click-modal='false' title="上传图片" :visible.sync="dialogVisible" @close="resetForm('addPictureSzRef')" width="400px">
        <el-form label-position="top" label-width="auto" size="medium" :hide-required-asterisk='true' :model="addPictureSzForm" :rules="addPictureSzRules" ref="addPictureSzRef">
            <el-form-item prop="material" style="margin-bottom:0">
                <div class="picture_list flexbox" v-if="addPictureSzForm.material.length>0">
                    <div class="picture_box flexbox flexjust" v-for="(item,index) in addPictureSzForm.material" :key="index">
                        <div class="delet_img flexbox flexcenter flexjust">
                            <span class="el-icon-delete" @click="deletImg(index)"></span>
                        </div>
                        <img :src="item.url" alt="">
                    </div>
                    <el-upload class="picture_box" drag :show-file-list="false" multiple :disabled="upload_disabled" action :http-request="imgUploadRequest" :before-upload="beforeImgUpload">
                        <img src="../../assets/img/add_icon.svg" alt="" width="40" height="40">
                    </el-upload>
                </div>
                <el-upload class="load-uploader" drag :show-file-list="false" multiple :disabled="upload_disabled" action :http-request="imgUploadRequest" :before-upload="beforeImgUpload" v-else>
                    <div class="pot_content flexbox flexcenter">
                        <img src="../../assets/img/pot_picture.svg" alt="">
                        <span class="pot_text">点击上传或直接将图片文件拖入此区域</span>
                        <span class="pot_tips">图片大小不超过10M，图片格式为 png、jpg</span>
                    </div>
                </el-upload>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="resetForm('addPictureSzRef')" size="small" class="el-button-width">取 消</el-button>
            <el-button type="primary" @click="submitForm('addPictureSzRef')" size="small" :disabled='disabled' :loading="disabled" class="el-button-width">完成</el-button>
        </span>
    </el-dialog>
</template>

<script>
import { clientInfo,clientTos,tosLink } from "../../assets/js/oss";
export default {
    name: "",
    data() {
        return {
            upload_disabled: false,
            disabled: false,
            disVideo: false,
            dialogVisible: false,
            optimiList: [],
            img_code: 0,
            is_change: 0,
            addPictureSzForm: {
                id: "",
                material: [],
            },
            addPictureSzRules: {},
        };
    },

    created() {
        this.$bus.on("addPictureSz", (value) => {
            this.addPictureSzForm.id = value.id;
            if (value.affected_rows == 0) {
                this.addPictureSzForm.material = [...value.material];
            } else {
                this.addPictureSzForm.material = [];
            }
            this.dialogVisible = value.dialogVsb;
            this.img_code = this.addPictureSzForm.material.length + 1;
        });
    },
    beforeDestroy() {
        this.$bus.off("addPictureSz");
    },
    methods: {
        // 图片上传格式验证
        beforeImgUpload(file) {
            var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            const extension =
                testmsg === "jpg" ||
                testmsg === "JPG" ||
                testmsg === "png" ||
                testmsg === "PNG" ||
                testmsg === "jpeg" ||
                testmsg === "JPEG" ||
                testmsg === "gif";
            const isLt2M = file.size / 1024 / 1024 < 10;
            if (!extension) {
                this.$message({
                    message: "上传图片只能是jpg / png格式!",
                    type: "error",
                });
                return false;
            }
            if (!isLt2M) {
                this.$message({
                    message: "上传文件大小不能超过 10MB!",
                    type: "error",
                });
                return false;
            }
            return extension || isLt2M;
        },
        // 图片上传到oss
        async imgUploadRequest(option) {
            const { data: res } = await this.$http.post(
                "adminapi/demandsz/pictureUploadName",
                {
                    id: this.addPictureSzForm.id,
                }
            );
            if (res.code !== 200) {
                this.disabled = false;
                this.$message.error(res.msg);
                return;
            } else {
                let code = this.img_code++;
                var testmsg = option.file.name.substring(
                    option.file.name.lastIndexOf(".")
                );
                var fileName = res.data.material_name + "_" + code + testmsg;
                try {
                    const client = clientInfo;
                    const clienttos = clientTos
                    let file = option.file;
                    let nowData = new Date();
                    let year = nowData.getFullYear();
                    let month =
                        nowData.getMonth() + 1 < 10
                            ? "0" + (nowData.getMonth() + 1)
                            : nowData.getMonth() + 1;
                    let date =
                        nowData.getDate() < 10
                            ? "0" + nowData.getDate()
                            : nowData.getDate();
                    let getData = year + "-" + month + "-" + date;
                    let relativePath = "source4.0/" + getData + "/";
                    const ret = await clienttos.putObject({
                        key: relativePath + fileName,
                        body: file,
                    });
                    if (ret.statusCode === 200) {
                        let url = tosLink+relativePath + encodeURIComponent(fileName)
                        this.addPictureSzForm.material.push({
                            url: url,
                            name: fileName,
                        });
                        this.$message({
                            message: "上传成功！",
                            type: "success",
                        });
                        this.is_change = 1;
                    } else {
                        this.is_change = 0;
                        this.$message.error("上传失败！");
                    }

                    // let ret = await client.put(relativePath + fileName, file);
                    // if (ret.res.statusCode === 200) {
                    //     this.addPictureSzForm.material.push({
                    //         url: ret.res.requestUrls[0],
                    //         name: fileName,
                    //     });
                    //     this.$message({
                    //         message: "上传成功！",
                    //         type: "success",
                    //     });
                    //     this.is_change = 1;
                    // } else {
                    //     this.is_change = 0;
                    //     this.$message.error("上传失败！");
                    // }
                } catch (error) {
                    this.is_change = 0;
                    this.$message.error("上传失败！");
                }
            }
        },

        // 提交添加
        submitForm(formName) {
            if (this.is_change == 0) {
                this.resetForm(formName);
            } else {
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        this.disabled = true;
                        const { data: res } = await this.$http.post(
                            "adminapi/demandsz/pictureUpload",
                            this.addPictureSzForm
                        );
                        if (res.code !== 200) {
                            this.disabled = false;
                            this.$message.error(res.msg);
                            return;
                        } else {
                            this.$message({
                                message: "上传成功",
                                type: "success",
                            });
                            this.disabled = false;
                            this.resetForm(formName);
                            this.$parent.getDataList(this.$parent.setpage);
                        }
                    } else {
                        this.disabled = false;
                        return false;
                    }
                });
            }
        },

        // 图片删除
        deletImg(index) {
            this.addPictureSzForm.material.splice(index, 1);
            this.is_change = 1;
        },

        // 关闭重置表单
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.addPictureSzForm.material = [];
            this.is_change = 0;
            this.dialogVisible = false;
        },
    },
};
</script>
<style scoped>
.pot_content {
    width: 100%;
    height: 181px;
    background-color: rgba(165, 177, 209, 0.08);
    border-radius: 12px;
    flex-direction: column;
    justify-content: center;
}
.pot_text {
    font-size: 13px;
    color: #25282c;
    line-height: 18px;
    margin-top: 12px;
}
.pot_tips {
    font-size: 13px;
    color: #828b99;
    margin-top: 4px;
    line-height: 18px;
}
.picture_list {
    height: 183px;
    flex-wrap: wrap;
}
.picture_box {
    width: 80px;
    height: 80px;
    border: 1px solid #ebebeb;
    border-radius: 4px;
    position: relative;
    overflow: hidden;
    margin-right: 10px;
}
.picture_box img {
    height: 100%;
}
.delet_img {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 2;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.2);
    display: none;
}
.delet_img span {
    font-size: 20px;
    color: #fff;
    cursor: pointer;
}
.picture_box:hover .delet_img {
    display: flex;
}
</style>
<style>
.load-uploader {
    width: 100%;
    height: 183px;
}
.load-uploader .el-upload {
    display: block;
}
.load-uploader .el-upload-dragger {
    width: 100%;
    height: 183px;
    border: 0;
}

.picture_box .el-upload-dragger {
    border: 0;
    width: 80px;
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>
